package currency

import (
	"bbtradeByGo/pkg/email"
	"bbtradeByGo/pkg/gmysql"
	"bbtradeByGo/pkg/logging"
	"database/sql"
	"fmt"
	"github.com/jmoiron/sqlx"
	"math"
	"strings"
	"time"
)

type Condition struct {
	Id            int           `json:"id"`
	CurrencyName  string        `json:"currency_name"`
	IsBasic       int           `json:"is_basic"`
	IdIn          []int         `json:"id_in"`
	Fields        interface{}   `json:"fields"`
	GroupBy       interface{}   `json:"group_by"`
	OrderBy       interface{}   `json:"order_by"`
	OrderByType   interface{}   `json:"order_by_type"`
	Limit         int           `json:"limit"`
	Offset        int           `json:"offset"`
	Status        int           `json:"status"`
	Pid           int           `json:"pid"`
	Cid           int           `json:"cid"`
	Bcid          int           `json:"bcid"`
	IsPair        bool          `json:"is_pair"`
}

type Count struct {
	BaseCurrencyId      int          `json:"base_currency_id"`
	CurrencyId          int          `json:"currency_id"`
	Amount              float64      `json:"amount"`
	AmountMoney         float64      `json:"amountMoney"`
	AmountMoneyRepeat   float64      `json:"amount_money_repeat"`
	PriceMax            float64      `json:"priceMax"`
	PriceMaxRepeat      float64      `json:"price_max_repeat"`
	PriceMin            float64      `json:"priceMin"`
	PriceMinRepeat      float64      `json:"price_min_repeat"`
	BaseAmount          float64      `json:"baseMmount"`
	BaseAmountRepeat    float64      `json:"base_amount_repeat"`
	PriceNew            float64      `json:"priceNew"`
	PriceNewRepeat      float64      `json:"price_new_repeat"`
	PriceOpen           float64      `json:"priceOpen"`
	PriceOpenRepeat     float64      `json:"price_open_repeat"`
}

type BaseList struct {
	Id            int            `json:"id"`
	PriceMax      float64        `json:"priceMax"`
	PriceMin      float64        `json:"priceMin"`
	Amount        float64        `json:"amount"`
	BaseAmount    float64        `json:"baseAmount"`
	PriceNew      float64        `json:"priceNew"`
	Increase      float64        `json:"increase"`
	PriceOpen     float64        `json:"priceOpen"`
	PriceBase     float64        `json:"price_base"`
	Dpc           int            `json:"dpc"`
	Npc           int            `json:"npc"`
	BuyPdg        float64        `json:"buy_pdg"`
	SellPdg       float64        `json:"sell_pdg"`
	BuyMin        float64        `json:"buy_min"`
	SellMin       float64        `json:"sell_min"`
	CurrencyName  string         `json:"currency_name"`
	IsPrimary     int            `json:"is_primary"`
	CurrencyImg   string         `json:"currency_img"`
	CurrencyType  int            `json:"currency_type"`
	CurrencyDescriptionCh string `json:"currency_description_ch"`
	CurrencyDescriptionEn string `json:"currency_description_en"`
	Trade []*BaseList
}

type PriceList struct {
	PriceNew      float64      `json:"priceNew"`
	Id            int          `json:"id"`
}

//CurrencyList 根据状态查询交易列表
func CurrencyList(c *Condition) ([]*BaseList, error){
	baseList := make([]*BaseList, 0)
	var (
		where      []string
		args       []interface{}
		query      string
	)
	if (c.Fields == ""){
		c.Fields = "*"
	}
	// 组合query
	query = fmt.Sprintf(`SELECT %s from abc_currency AS a where is_del=0`, c.Fields)
	if c.IsPair == true{
		query = fmt.Sprintf(`SELECT %s from abc_currency_pair AS a left join abc_currency AS b on a.cid = b.id where a.is_del=0 `, c.Fields)
	}
	if len(c.IdIn) > 0 {
		q, a, err := sqlx.In("a.id in (?)", c.IdIn)
		if err != nil {
			return nil, err
		}
		where = append(where, q)
		args = append(args, a...)
	}

	if c.Id != 0 {
		where = append(where, ` and a.id = ?`)
		args = append(args, c.Id)
	}

	if c.CurrencyName != ""{
		where = append(where, ` and a.currency_name = ?`)
		args = append(args, c.CurrencyName)
	}
	if c.IsBasic != 0{
		where = append(where, ` and a.is_basic = ?`)
		args = append(args, c.IsBasic)
	}
	if c.Pid != 0{
		where = append(where, ` and a.pid = ?`)
		args = append(args, c.Pid)
	}
	if c.Cid != 0{
		where = append(where, ` and a.cid = ?`)
		args = append(args, c.Cid)
	}
	if c.Status != 0{
		where = append(where, ` and a.status = ?`)
		args = append(args, c.Status)
	}
	if c.Bcid != 0{
		where = append(where, ` and a.bcid = ?`)
		args = append(args, c.Bcid)
	}
	if len(where) > 0 {
		query = query +strings.Join(where, " ")
	}

	if (c.Limit != 0 && c.Offset != 0){
		query = query + " LIMIT ? OFFSET ?"
		args = append(args, c.Limit, c.Offset)
	}

	if (c.OrderBy != nil){
		query = query + " ORDER BY ? ?"
		args = append(args, c.OrderBy, c.OrderByType)
	}

	if (c.GroupBy != nil){
		query = query + " GROUP BY ? "
		args = append(args, c.GroupBy)
	}
	query = gmysql.DB.Rebind(query)
	if err := gmysql.DB.Unsafe().Select(&baseList, query, args...); err != nil {
		if err != sql.ErrNoRows {
			return nil, err
		}
	}
	return baseList, nil
}

// TradeCount24 24小时交易统计
func TradeCount24(base_currency_id int, currency_id int) ([]*Count, error){
	count := make([]*Count, 0)
	begin := math.Round(float64(time.Now().Unix())) - float64(60 * 60 * 24)
	end   := math.Round(float64(time.Now().Unix()))
	if err := gmysql.DB.Select(&count,`SELECT
                        IFNULL(SUM(number), 0.0) AS amount,
                        IFNULL(number * price, 0.0) AS amount_money_repeat,
                        IFNULL(MAX(price), 0.0) AS price_max_repeat,
                        IFNULL(price, 0.0) AS price_min_repeat,
                        IFNULL(SUM(number * price),0.0) as base_amount_repeat
                    FROM
                        abc_trade
                    WHERE
                        base_currency_id = ?
                    AND currency_id = ?
                    AND type = 1 
                    AND create_time >= ?
                    AND create_time <= ?`, base_currency_id, currency_id, begin, end); err != nil{
                    	email.SendMail("model.currency.tradecount24", err.Error())
                    	logging.Error("model.currency.currency TradeCount24 err: ",err)
                    	return nil, err
	}
      return count, nil
}

//TradeNew 统计交易价格
func TradeNew(base_currency_id, currency_id int) ([]*Count, error){
	count := make([]*Count, 0)
    if err := gmysql.DB.Select(&count, `SELECT
                        price AS price_new_repeat
                    FROM
                        abc_trade
                    WHERE
                        base_currency_id = ?
                    AND currency_id = ?
                    ORDER BY
	                    create_time DESC
                    LIMIT 1`, base_currency_id, currency_id); err != nil {
		email.SendMail("model.currency.tradenew", err.Error())
		logging.Error("model.currency.currency.go TradeNew err: \n", err)
		return nil, err
	}
                    return count, nil
}

//TradeCount24Open 统计24h交易价格
func TradeCount24Open(base_currency_id, currency_id int) ([]*Count, error){
	count := make([]*Count, 0)
	timestamp := math.Round(float64(time.Now().Unix())) - float64(60 * 60 * 24)
	if err := gmysql.DB.Select(&count, `SELECT
                        price AS price_open_repeat
                    FROM
                        abc_trade
                    WHERE
                        base_currency_id = ?
                    AND currency_id = ?
                    AND create_time > ?
                    ORDER BY
	                    create_time ASC
                    LIMIT 1`, base_currency_id, currency_id, timestamp); err != nil{
		email.SendMail("model.currency.tradecount24open", err.Error())
		logging.Error("model.currency.currency.go TradeCount24Open err: \n", err)
		return nil, err
	}
	return count, nil
}






















